/*
 * HeFengWeatherService.java
 * Copyright 2025 Churan Tech, all rights reserved.
 * Churan PROPRIETARY/CONFIDENTIAL, any form of usage is subject to approval.
 */

package com.churan.ai.mcp.server.weather.service;

import com.churan.ai.core.exception.McpException;
import com.churan.ai.mcp.server.weather.vo.GeoLocationVO;
import com.churan.ai.mcp.server.weather.vo.WeatherDomain;
import com.churan.ai.mcp.server.weather.vo.WeatherVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * Function: 和风天气api对接
 *
 * @author churan
 * @date: 2025年5月7日
 */
@Service
@Slf4j
public class HeFengWeatherService {

    @Value("${hf.api_key}")
    private String apiKey;
    @Value("${hf.geo_api_url}")
    private String geoApiUrl;
    @Value("${hf.weather_api_url}")
    private String weatherApiUrl;

    @Resource
    private RestTemplate restTemplate;

    /**
     * 根据城市名字获取试试天气
     *
     * @param name
     * @return
     */
    @Tool(name = "getCurrentWeatherByHfApi", description = "根据城市名称拼音查询实时天气")
    public String getCurrentWeather(@ToolParam(description = "城市名称拼音") String name) {
        return remoteWeather(name).toString();
    }

    /**
     * 查询天气
     *
     * @param city
     * @return
     */

    private WeatherVO remoteWeather(String city) {
        final String locationId = remoteCityLocationId(city);
        final String weatherUrl = UriComponentsBuilder.fromUri(URI.create(weatherApiUrl))
                .queryParam("location", locationId)
                .queryParam("key", apiKey)
                .encode().toUriString();
        try {
            final WeatherDomain weatherDomain = restTemplate.getForObject(weatherUrl, WeatherDomain.class);
            if (Objects.isNull(weatherDomain)) {
                throw new McpException("未获取到对应天气信息");
            }
            return convertVo(weatherDomain);
        } catch (HttpClientErrorException e) {
            throw new McpException("天气API调用失败: " + e.getStatusCode());
        }
    }

    /**
     * 查询城市经纬度id
     *
     * @param city
     * @return
     */
    @Tool(name = "getCityLocationIdByHfApi", description = "根据城市名称查询经纬度id")
    public String remoteCityLocationId(String city) {
        final String geoUrl = UriComponentsBuilder.fromUri(URI.create(geoApiUrl))
                .queryParam("location", city)
                .queryParam("key", apiKey)
                .encode().toUriString();

        try {
            final GeoLocationVO GeoLocationVo = restTemplate.getForObject(geoUrl, GeoLocationVO.class);
            if (Objects.nonNull(GeoLocationVo) && !CollectionUtils.isEmpty(GeoLocationVo.getLocation())) {
                return GeoLocationVo.getLocation().get(0).getId();
            }
        } catch (Exception e) {
            log.error("MCP_TOOL_ERROR", e);
            throw new McpException("获取城市经纬度发生错误: " + e.getMessage());
        }
        return null;
    }

    private WeatherVO convertVo(final WeatherDomain domain) {
        return new WeatherVO(LocalDateTime.now(), domain.getNow().getTemp(), domain.getNow().getText(), domain.getNow().getWindDir(), domain.getNow().getHumidity());
    }
}
